#!/usr/bin/env ruby -wKU
#encoding: UTF-8

require 'nokogiri'
require 'open-uri'

require 'backend/model/Tieba'
require 'backend/model/TNovel'

module TiebaConfig
  
  class ConfigLoader
    
    def initialize(configXml)
      @configXml = configXml
    end
    
    def load
      tiebaInstance = Model::Tieba.instance
      
      xml = Nokogiri::XML(open(@configXml))
      novels = xml.xpath("//novel")
      return if novels.nil? || novels.length == 0
      
      novels.each do |n|
        tieba = n.at_xpath("tieba").content
        top = n.at_xpath("top").content
        name = n.at_xpath("name").content
        author = n.at_xpath("author").content
        
        # puts tieba, top, name, author
        # puts n.xpath("tieba")
        
        if tieba.nil? || name.nil? || author.nil?
          $logger.error(__FILE__) { "line " + __LINE__.to_s + "=> configuration is incomplete " + n.to_s }
          next
        end
        # raise ArgumentError.new("config.xml error") if tieba.nil? || name.nil? || author.nil?
        
        onTop = false
        onTop = true if top.nil? || top.downcase == 'true'
        
        novel = Model::TNovel.new
        novel.tiebaName = tieba unless tieba.nil?
        novel.author = author unless author.nil?
        novel.novelName = name unless novel.nil?
        novel.onTop = onTop
        
        tiebaInstance.addNovel(novel)
      end
      
    end
    
  end
  
end
